package com.example.streamtransport.Controller;

import com.example.streamtransport.Event.OrderEvent;
import com.example.streamtransport.Model.BussinessRequest;
import com.example.streamtransport.Model.EmptyRequest;
import com.example.streamtransport.Model.TestARequest;
import com.example.streamtransport.Service.UserService;
import com.mediator.Mediator.IMediator;
import com.mediator.Mediator.impl.Mediator;
import jakarta.servlet.http.HttpServletResponse;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.FileReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.*;

@RestController

@RequestMapping("Hello")
public class HelloController {

    @Autowired
    private IMediator mediator;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    public HelloController() {
    }
   private String Appid="408035";
    private String Appsecret="PgZgD80aWLrQUxlhVD452aJl";
    @GetMapping(value = "/GetHello", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> GetHello() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> "Event " + sequence);
    }
    @PreAuthorize(Name="")
    @GetMapping(value = "/GetHellos", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void GetHellos(HttpServletResponse response) throws Exception
    {
        var event=new OrderEvent("");
        event.Name="11111";
        mediator.Send(new EmptyRequest());
        var a=mediator.Send(new TestARequest());
        var b=mediator.Send(new BussinessRequest());
        applicationEventPublisher.publishEvent(event);
        if (response.containsHeader("Content-Type"))
        {
            response.setHeader("Content-Type","text/event-stream");
        }
        else
        {
            response.setHeader("Content-Type","text/event-stream");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Connection", "keep-alive");
        }
        String data ="id:"+new Random().nextInt() +" \n" +
            "retry: "+new Random().nextInt(0,100)*30+"\n" +
            "event: message\n" +
            "data: "+new Random().nextInt()+"\n\n";
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(data);
    }

}
